import { MessageBar, MessageBarType, PrimaryButton, TextField } from "@fluentui/react";
import { useContext, useEffect, useState } from "react";
import { isValidLocalPath } from "../utils";
import { open } from '@tauri-apps/api/dialog';
import { GlobalContext } from "../Context/global";
import { RS, tk } from "../../i18n/config";
import i18next from "i18next";

interface IProps {
    getDependenceVersion: (forguncyPath: string, prefix: string) => Promise<string>;//返回依赖版本
    apiName: string;
    apiDisplayName?: string;
}

function useInstallPath(props: IProps) {
    const { context: { forguncyPath }, dispatch } = useContext(GlobalContext);
    const [depVersion, setJarVersion] = useState("");
    const forguncyPathValid = forguncyPath.length > 0 && isValidLocalPath(forguncyPath) && depVersion.length > 0;
    const setForguncyPathHandle = (path: string) => {
        dispatch?.({ type: 'forguncyPath', payload: path });
    }
    useEffect(() => {
        props.getDependenceVersion(forguncyPath, props.apiName).then((ver) => setJarVersion(ver));
    }, [forguncyPath]);
    const selectForguncyPath = () => {
        open({
            directory: true,
            multiple: false
        }).then((directory) => {
            if (directory) {
                var dir = typeof directory === 'string' ? directory : directory[0];
                setForguncyPathHandle(dir);
            }
        });
    }
    const dom = <>
        <div style={{ display: 'flex', justifyContent: 'stretch', alignItems: 'flex-start', width: "100%" }}>
            <TextField
                className="installPath"
                label={RS.Forguncy_Install_Path}
                maxLength={150}
                errorMessage={forguncyPathValid ? undefined : RS.Forguncy_Java_plugin_support_file_not_found}
                required
                value={forguncyPath}
                onChange={ev => setForguncyPathHandle((ev.target as HTMLInputElement).value)} />
            <PrimaryButton style={{ width: '24px', marginLeft: '8px', marginTop: '34px' }} onClick={selectForguncyPath}>{RS.Select}</PrimaryButton>
        </div>

        {
            forguncyPathValid ? <MessageBar
                messageBarType={MessageBarType.success}
                isMultiline={true}
            >
                {i18next.t(tk.Found_Support_file_version, { a: props.apiDisplayName || props.apiName, b: depVersion })}
            </MessageBar> : ""
        }
    </>;
    return [dom, forguncyPath, forguncyPathValid, depVersion, setForguncyPathHandle] as const;
}
export default useInstallPath;